<?php

namespace App\Services;

use App\Models\ElementModel;
use App\Models\FloorModel;
use App\Traits\HelperTrait;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ElementService extends BaseService
{
    use HelperTrait;

    protected $error_msg = '';

    /**
     * Notes: 获取单元和楼层列表
     * User: lstink
     * Date: 2021/2/4
     * Time: 10:48 上午
     * @param $where
     * @return mixed
     */
    public function getElementList($where, $param)
    {
        return FloorModel::whereHas('house', function ($query) use ($param) {
            //楼栋
            if (!empty($param['house_num'])) {
                $query->where('house_num', $param['house_num']);
            }
        })->whereHas('element', function ($query) use ($param) {
            //单元
            if (!empty($param['element_num'])) {
                $query->where('element_num', $param['element_num']);
            }
        })->with(['community', 'house', 'element'])->where($where)->where(function ($query) use ($param) {
            //楼层
            if (!empty($param['floor'])) {
                $query->where('floor', $param['floor']);
            }
            //小区
            if (!empty($param['c_id'])) {
                $query->where('c_id', $param['c_id']);
            }
        })->paginate($param['per_page'] ?? 30);
    }

    public function addElement($data, $estate_id)
    {
        //验证数据
        $validator = Validator::make($data, [
            'community_id' => 'required',
            'h_id'         => 'required',
            'element'      => 'required',
            'floor'        => 'required',
        ], [
            'community_id.required' => '请选择小区！',
            'h_id.required'         => '请选择楼号！',
            'element.required'      => '请填写单元号！',
            'floor.required'        => '请填写楼层！',
        ]);
        if ($validator->fails()) {
            $this->error_msg = $validator->errors()->first();
            return false;
        }
        //处理楼层信息
        return $this->handleHouse($data, $estate_id);
    }

    /**
     * Notes: 处理楼栋数据
     * User: lstink
     * Date: 2021/2/4
     * Time: 10:00 上午
     * @param $data [传输的数据]
     * @param $estate_id [物业id]
     * @return mixed
     */
    protected function handleHouse($data, $estate_id)
    {
        $element = [];
        if ($this->isMul($data['element'])) {
            $arr = explode('-', $data['element']);
            $arr = array_filter($arr);
            //批量添加
            for ($i = $arr[0]; $i <= $arr[1]; $i++) {
                $element[] = [
                    'estate_id'   => $estate_id,
                    'c_id'        => $data['community_id'],
                    'h_id'        => $data['h_id'],
                    'element_num' => $i,
                ];
            }
        } else {
            //单个添加
            $element[] = [
                'estate_id'   => $estate_id,
                'c_id'        => $data['community_id'],
                'h_id'        => $data['h_id'],
                'element_num' => $data['element'],
            ];
        }
        //开启事务
        DB::beginTransaction();
        try {
            //遍历所有单元
            foreach ($element as $item) {
                //添加单元
                $element_info = ElementModel::firstOrCreate(['c_id' => $item['c_id'], 'h_id' => $item['h_id'], 'element_num' => $item['element_num']], $item);
                //添加单元对应的楼层
                $floor = [];
                if ($this->isMul($data['floor'])) {
                    $arr = explode('-', $data['floor']);
                    $arr = array_filter($arr);
                    //批量添加
                    for ($i = 1; $i <= $arr[1]; $i++) {
                        $floor[] = [
                            'estate_id' => $estate_id,
                            'c_id'      => $data['community_id'],
                            'h_id'      => $data['h_id'],
                            'floor'     => $i,
                        ];
                    }
                } else {
                    //单个添加
                    $floor[] = [
                        'estate_id' => $estate_id,
                        'c_id'      => $data['community_id'],
                        'h_id'      => $data['h_id'],
                        'floor'     => $data['floor'],
                    ];
                }
                $element_info->floor()->createMany($floor);
            }
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            $this->error_msg = '存在已有单元号或者楼层，请勿重复添加';
            return false;
        }

        return true;
    }

    /**
     * Notes: 判断是否为批量添加
     * User: lstink
     * Date: 2021/2/3
     * Time: 3:57 下午
     * @param $value [值]
     * @return bool
     */
    protected function isMul($value)
    {
        if (strpos($value, '-') === false) {
            return false;
        }

        return true;
    }

    /**
     * Notes: 获取错误信息
     * User: lstink
     * Date: 2021/2/4
     * Time: 10:02 上午
     * @return string
     */
    public function getMessage()
    {
        return $this->error_msg;
    }
}
